<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item v-if="formType === 'create'" label="鸡舍类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择鸡舍类型" @change="handleChangeType">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.FARM_FARMHOUSE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item v-if="formType === 'create'" label="农舍" prop="houseId">
        <el-select v-model="formData.houseId" placeholder="请选择农舍">
          <el-option 
            v-for="item in houseList" 
            :key="item.id" 
            :label="item.houseName" 
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="进舍总数" prop="inNum">
        <el-input-number v-model="formData.inNum" placeholder="请输入进舍总数" style="width:250px" />
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input  v-model="formData.description" type="textarea"  />
      </el-form-item>
      <el-form-item label="入舍日期" prop="inFarmhouseTime">
        <el-date-picker
          v-model="formData.inFarmhouseTime"
          type="date"
          value-format="x"
          placeholder="选择入舍日期"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { PcApi } from '@/api/farm/pc'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = reactive({
  id: undefined,
  houseId: undefined,
  houseName:'',
  pcId: 0,
  type: '',
  preId: -1,
  inNum: undefined,
  num: undefined,
  eliminateTime: undefined,
  eliminateFinishTime: undefined,
  description: undefined,
  inFarmhouseTime: undefined,
})
const formRules = reactive({
  houseId: [{ required: true, message: '农舍还未选择', trigger: 'change' }],
  pcId: [{ required: true, message: '批次不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '鸡舍类型不能为空', trigger: 'change' }],
  preId: [{ required: true, message: '记录先前数据不能为空', trigger: 'blur' }],
  inNum: [{ required: true, message: '进舍总数不能为空', trigger: 'blur' }],
  num: [{ required: true, message: '剩余数量不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref


const houseList =ref([])//农舍

/** 打开弹窗 */
//type:'create'||'update'
const open =async(type: string,id: number,pcId:number,activeHouseType: string) => {
// const open = async ({type,pcId, id}:{type: string,pcId:number,id: number}) => {
  dialogTitle.value = t('action.' + type)
  dialogVisible.value = true
  formType.value = type
  // console.log(formType,'formType');
  resetForm()
  formData.pcId = pcId
  formData.type =activeHouseType
  getHouseList(activeHouseType)
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const formDataRes =await PcApi.getInFarmhouse(id)
      if(formDataRes){
        Object.assign(formData,formDataRes)
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData
    if (formType.value === 'create') {
      await PcApi.createInFarmhouse(data)
      message.success(t('common.createSuccess'))
    } else {
      await PcApi.updateInFarmhouse(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  Object.assign(formData,{
    id: undefined,
    houseId: undefined,
    pcId: undefined,
    type: undefined,
    preId: -1,
    inNum: undefined,
    num: undefined,
    eliminateTime: undefined,
    eliminateFinishTime: undefined,
    description: undefined,
    inFarmhouseTime: undefined,
  })
  formRef.value?.resetFields()
}




// 获取农舍下拉列表
const getHouseList =async(type:string) =>{
  // console.log(type,'type');

  // 将 type 作为 params 对象的一个属性传递
  await PcApi.houseListApi({type}).then(res=>{
    // console.log(res,'res');
    houseList.value =res
    console.log(houseList.value,'houseList.value');
    
  })
}
const handleChangeType =(newType)=>{
    formData.houseId = undefined; // 清空农舍选择
    getHouseList(newType)
}

// 监听变化
// watch(()=>formData.type,(newType)=>{
//   if(newType){
//     formData.houseId = undefined; // 清空农舍选择
//     getHouseList(newType)
//   }

// })
</script>